package it.uai.domainsMigrator;
import java.util.Vector;

import org.apache.log4j.Logger;

public class Controller implements Runnable {
	
	private static final Logger logger = Logger.getLogger(Controller.class);

	Integer maxItemForSingleTransfert;
	ThreadManager sincronizzatore;
	Integer contatore = 0;
	Vector<Thread> vettoreThread = new Vector<Thread>();
	Domain dominio;
	Integer contatoreFile;
	Integer contatoreDirectory;
	Integer statisticsPrintPeriod;

	public Controller(Domain dominio, Integer maxThread, Integer maxItemForSingleTransfert, Integer statisticsPrintPeriod) {

		this.maxItemForSingleTransfert = maxItemForSingleTransfert;
		sincronizzatore = new ThreadManager(maxThread);
		this.dominio = dominio;
		this.statisticsPrintPeriod = statisticsPrintPeriod;
		
		contatoreFile = dominio.countFile();
		contatoreDirectory = dominio.countDirectory();
		
		logger.info("DOMINIO: " + dominio.getNome()	+ " - TOTALE DIRECTORY: " + contatoreDirectory	+ " - TOTALE FILE: " + contatoreFile);
		
		makeDirectories();

	}
	
	public void makeDirectories(){
		
		FtpMakeDirectories ftpMkdir = new FtpMakeDirectories();
		ftpMkdir.makeDir(dominio.getFtpServer(), dominio.getFtpUser(), dominio.getFtpPassword(), dominio.getDestinationPath(), dominio.getSourcePath(),dominio.getDirectories());
		logger.debug("Directory create");
	}

	@Override
	public void run() {

		logger.debug("Start controller");
		
		Statistiche stat = new Statistiche(dominio, statisticsPrintPeriod);
		Thread statThread = new Thread(stat);
		statThread.start();

		try {

			while (dominio.existItemNoAssigned()) {

				while (sincronizzatore.isFull()) {
					synchronized (sincronizzatore) {
						sincronizzatore.wait();
					}
				}
				
				FtpTransporter ftpThread = new FtpTransporter(sincronizzatore, maxItemForSingleTransfert);

				ftpThread.connectionSetup(dominio);
				
				Thread t = new Thread(ftpThread);
				sincronizzatore.enter();
				vettoreThread.add(t);
				t.start();
				logger.trace("Avviato thread: " + vettoreThread.indexOf(t));
				contatore++;

			}

			for (Thread t : vettoreThread) {
				t.join();				
			}
			statThread.interrupt();
			dominio.printStatistics();			
			dominio.setProcessed();		

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.debug("End controller");

	}

}
